package com.inventory.form;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.inventory.persistence.ProductType;
import com.inventory.service.product.ProductTypeService;

public class ProductTypeValidator implements Validator {

	@Autowired
	private ProductTypeService productTypeService;

	@Override
	public boolean supports(Class<?> clazz) {
		return ProductTypeForm.class.equals(clazz);
	}

	@Override
	public void validate(Object target, Errors errors) {
		ProductTypeForm form = (ProductTypeForm) target;
		List<ProductType> dbProductTypes = productTypeService.getAllProductTypes();
		ProductType[] productTypesArray = form.getProductTypes();
		for (ProductType productType : dbProductTypes) {
			for (ProductType productTypeArray : productTypesArray) {
				if (productTypeArray.getCategory().equals(productType.getCategory())) {
					errors.reject("errors.productType.duplicate");
					return;
				}
			}
		}

	}

	public void setProductTypeService(ProductTypeService productTypeService) {
		this.productTypeService = productTypeService;
	}
}
